package org.tloss.web.editor.utils;

import java.util.ArrayList;
import java.util.List;

import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.Viewer;

public class VariableListProvider implements ITreeContentProvider {
	@Override
	public void dispose() {

	}

	@Override
	public void inputChanged(Viewer arg0, Object arg1, Object arg2) {

	}

	@Override
	public Object[] getChildren(Object arg0) {
		return getElements(arg0);
	}

	FactoryVariable factoryVariable = new FactoryVariable();

	@Override
	public Object[] getElements(Object arg0) {
		if (arg0 != null) {
			if (arg0 instanceof List) {
				List<VariableGroup> groups = new ArrayList<VariableGroup>();
				VariableGroup entityGroup = new VariableGroup("Entities") {
					public boolean supportedVairable(Variable variable) {
						return variable != null
								& variable instanceof EntityVariable;
					}

				};
				groups.add(entityGroup);
				VariableGroup formField = new VariableGroup("Form") {

					public boolean supportedVairable(Variable variable) {
						return variable != null
								& variable instanceof FormFieldVariable;
					}

				};

				groups.add(formField);
				VariableGroup message = new VariableGroup("Message") {

					public boolean supportedVairable(Variable variable) {
						return variable != null
								& variable instanceof MessageVairable;
					}

				};
				groups.add(message);
				List<?> list = (List<?>) arg0;
				for (int i = 0; i < list.size(); i++) {
					List<Variable> variables = factoryVariable
							.createVariable(list.get(i));
					if (variables != null) {
						for (int k = 0; k < variables.size(); k++) {
							for (int j = 0; j < groups.size(); j++) {
								if (groups.get(j).supportedVairable(
										variables.get(k))) {
									factoryVariable.initParent(groups.get(j),
											variables.get(k));
								}
							}
						}
					}
				}
				return groups.toArray();
			} else if (arg0 instanceof Variable) {
				List<Variable> list = ((Variable) arg0).getChildren();
				if (list != null) {
					return list.toArray();
				}
			}
		}
		return Constants.EMPTY_ARRAY;
	}

	@Override
	public Object getParent(Object arg0) {
		if (arg0 != null) {
			if (arg0 instanceof Variable) {
				return ((Variable) arg0).getParent();
			}
		}
		return null;
	}

	@SuppressWarnings("rawtypes")
	@Override
	public boolean hasChildren(Object arg0) {
		if (arg0 != null) {
			if (arg0 instanceof List) {
				return !((List) arg0).isEmpty();
			} else if (arg0 instanceof Variable) {
				return ((Variable) arg0).hasChildren();
			}
		}
		return false;
	}

}
